#!/usr/bin/env python
#-*- coding:utf-8 -*-

'''sscmlocker

Automatic checkout the files from source scm when commit a changeset into local repository.

Usage:
Add follow content to hgrc file in your local hg reposity.
--------------------------------------
[extensions]
sscmsyncer = path\to\sscmlocker.py

[sscm]
rootrepository = Spread_for_WPF_SSL\
--------------------------------------
'''

import os
from mercurial import hg

#def preupdatehook(ui, repo, **kwargs):
#    print("Pre-update hook triggered")

def commithook(ui, repo, **kwargs):
    #ui.write([(key, kwargs[key]) for key in kwargs])
    #ui.write('\r\n')
    
    node = kwargs['node']
    rootrepository = ui.config("sscm", "rootrepository");
    
    for rev in xrange(repo[node], len(repo)):
        ctx = repo[rev]
        #ui.write(ctx)
        for f in ctx.files():
            cmd = ' co "{0}{1}" -c-'.format(rootrepository, f)
            ui.write("sscm " + cmd)
            ui.write('\r\n')
            os.execlp('sscm', cmd)

            
def uisetup(ui):
    # When pre-<cmd> and post-<cmd> hooks are configured by means of
    # the ui.setconfig() function, you must use the ui object passed
    # to uisetup or extsetup.
    
    #ui.setconfig("hooks", "pre-update.sscmlocker", preupdatehook)
    pass

def reposetup(ui, repo):
    # Repository-specific hooks can be configured here. These include
    # the update hook.
    
    rootrepository = ui.config("sscm", "rootrepository");
    if not rootrepository:
        return

    ui.setconfig("hooks", "commit.sscmlocker", commithook)